class PostsController < ApplicationController
  before_action :authenticate_user!, only: [:new, :edit, :create, :update, :destroy]
  before_action :set_post, only: [:show]
  before_action :set_post_for_current_user, only: [:edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    page = params[:page] || 1
    per = params[:per] || 20
    @posts = Post.all.page(page).per(per)
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    new_post = @post.custom_clone
    respond_to do |format|
      if @post.update(post_params)
        new_post.save!
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    Post.transaction do
      @post.versions.delete_all
      @post.destroy!
    end
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

  def set_post_for_current_user
    @post = current_user.posts.find_by(slug: params[:slug])
    raise ActiveRecord::RecordNotFound if @post.blank?
  end

  def set_post
    @post = Post.find_by(slug: params[:slug])
    raise ActiveRecord::RecordNotFound if @post.blank?
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def post_params
    params.require(:post).permit(:title, :body)
  end
end
